import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'

import { paginate } from '~/helper/paginate'
import { Pagination } from '~/helper/paginate/pagination'
import { PostEntity } from '~/modules/system/post/post.entity'
import { UserEntity } from '~/modules/system/user/user.entity'

import { PostQueryDto, PostSaveDto, PostSimpleDto } from './post.dto'

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(PostEntity)
    private postRepository: Repository<PostEntity>,
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
  ) {}

  /**
   * 获取岗位分页列表
   */
  async page({
    page,
    pageSize,
    code,
    name,
    status,
  }: PostQueryDto): Promise<Pagination<PostEntity>> {
    const queryBuilder = this.postRepository
      .createQueryBuilder('post')
      .orderBy({ sort: 'ASC' })
      .where({
        ...(code && { code: Like(`%${code}%`) }),
        ...(name && { name: Like(`%${name}%`) }),
        ...(status !== undefined && { status }),
      })

    return paginate(queryBuilder, { page, pageSize })
  }

  /**
   * 获取岗位列表（不分页）
   */
  async list({
    code,
    name,
    status,
  }: PostQueryDto): Promise<PostEntity[]> {
    return this.postRepository.find({
      where: {
        ...(code && { code: Like(`%${code}%`) }),
        ...(name && { name: Like(`%${name}%`) }),
        ...(status !== undefined && { status }),
      },
      order: { sort: 'ASC' },
    })
  }

  /**
   * 获取岗位简单列表
   */
  async getSimpleList(): Promise<PostSimpleDto[]> {
    const posts = await this.postRepository.find({
      select: ['id', 'name'],
      where: { status: 0 }, // 只返回正常状态的岗位
      order: { sort: 'ASC' },
    })

    return posts.map(post => ({
      id: post.id,
      name: post.name,
    }))
  }

  /**
   * 查询岗位详情
   */
  async findOne(id: number): Promise<PostEntity> {
    return this.postRepository.findOneBy({ id })
  }

  /**
   * 创建岗位
   */
  async create(dto: PostSaveDto): Promise<void> {
    await this.postRepository.insert(dto)
  }

  /**
   * 更新岗位
   */
  async update(id: number, dto: Partial<PostSaveDto>): Promise<void> {
    await this.postRepository.update(id, dto)
  }

  /**
   * 删除岗位
   */
  async delete(id: number): Promise<void> {
    await this.postRepository.delete(id)
  }

  /**
   * 获取用户岗位列表
   */
  async getUserPosts(userId: number): Promise<PostEntity[]> {
    const user = await this.userRepository.findOne({
      where: { id: userId },
      relations: ['posts'],
    })

    return user?.posts || []
  }

  /**
   * 设置用户岗位
   */
  async setUserPosts(userId: number, postIds: number[]): Promise<void> {
    const user = await this.userRepository.findOne({
      where: { id: userId },
      relations: ['posts'],
    })

    if (!user) {
      throw new Error('用户不存在')
    }

    // 获取岗位实体
    const posts = await this.postRepository.findByIds(postIds)

    // 设置用户岗位
    user.posts = posts
    await this.userRepository.save(user)
  }

  /**
   * 获取岗位用户数量
   */
  async countUsersByPostId(postId: number): Promise<number> {
    const post = await this.postRepository.findOne({
      where: { id: postId },
      relations: ['users'],
    })

    return post?.users?.length || 0
  }
}
